import axios from 'axios'
import md5 from 'crypto-js/md5';
import { useGlobeStore } from "@/stores";

const p = window.location.protocol
const baseURL = (process.env.NODE_ENV === "development")
  ? `${p}//api2.lotmaster.cn/api/`
  : `${p}//${baseUrlPro}/api/`;

axios.defaults.withCredentials = true
const service = axios.create({
  timeout: 30000, // 请求超时时间
  baseURL,
  headers: {
    // 'Accept': 'application/json',
    // 'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json',
    Authorization: '7387028416{|}f8fc6b68cb9badb5aed9b472174485f6',
  }
})

// 请求拦截器
service.interceptors.request.use((config) => {
  config.url = "v1." + config.url;
  if (config.loading) {
    showLoadingToast({ message: "加载中...", forbidClick: true, loadingType: 'spinner', duration: 0 });
  }
  return config
}, (error) => {
  console.log("request err:", error)
})

// 响应拦截器
service.interceptors.response.use((res) => {
  if (res.config.loading) {
    closeToast();
  }
  switch (res.data.code) {
    case 0:
      return res.data.data;
    case 4:
      useGlobeStore().setExpirePopup(true);
      break;
    default:
      if (res.data.msg) showToast(res.data.msg);
      break;
  }
}, (error) => {
  closeToast();
  console.log("response err:", error)
})

//只会调用一次接口，共享返回的promise
function query(requestHash, fun, ...params) {
  const res = JSON.parse(sessionStorage.getItem(requestHash));
  if (!res) {
    //不存在就请求
    return fun(...params).then(response => {
      sessionStorage.setItem(requestHash, JSON.stringify(response));
      return response;
    }).catch(function (error) {
      throw error;
    });
  } else {
    //存在就返回本地存储中的数据
    return res;
  }
}
export const http_share = (...params) => {
  var url = params[0];
  var requestHash = md5(url + JSON.stringify(params)).toString();
  return query(requestHash, service, ...params);
};
export default service;
